<template>
    <Header />
    <div class="greenhouse-container">
        <div class="greenhouse">
            <div class="button-container">
                <el-button type="primary" @click="handleAdd">新增大棚</el-button>
            </div>
            <div class="table">
                <el-table :data="greenhouses" border style="width: 80%" :header-cell-style="{ textAlign: 'center' }"
                    :cell-style="{ textAlign: 'center' }">
                    <el-table-column prop="name" label="名称"></el-table-column>
                    <el-table-column prop="location" label="位置"></el-table-column>
                    <el-table-column prop="area" label="面积"></el-table-column>
                    <el-table-column label="状态">
                        <template #default="scope">
                            <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
                                @change="handleChangeStatus(scope.row)"></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建日期">
                        <template #default="scope">
                            {{ formatDate(scope.row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 新增/编辑对话框 -->
            <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%">
                <el-form :model="form">
                    <el-form-item label="名称" :label-width="formLabelWidth">
                        <el-input v-model="form.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="位置" :label-width="formLabelWidth">
                        <el-input v-model="form.location" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="面积" :label-width="formLabelWidth">
                        <el-input v-model.number="form.area" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="handleConfirm">确 定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue';
import Header from '@/components/Header.vue';
import { get } from '@/api/request';
import { ElMessage } from 'element-plus';

// 模拟数据
const greenhouses = ref([]);

const dialogVisible = ref(false);
const form = reactive({
    id: null,
    name: '',
    location: '',
    area: null,
});
const formLabelWidth = '100px';
const dialogTitle = ref('新增大棚');

const handleAdd = () => {
    dialogTitle.value = '新增大棚';
    resetForm();
    dialogVisible.value = true;
};

const handleEdit = (row) => {
    dialogTitle.value = '编辑大棚';
    form.id = row.id;
    form.name = row.name;
    form.location = row.location;
    form.area = row.area;
    form.status = row.status;
    dialogVisible.value = true;
};

const resetForm = () => {
    form.id = null;
    form.name = '';
    form.location = '';
    form.area = null;
};

const getStatusText = (status) => {
    return status === 1 ? '启用' : '停用';
};

const formatDate = (date) => {
    return date ? new Date(date).toLocaleDateString() : '';
};

const fetchGreenhouses = async () => {
    try {
        const response = await get('/greenhouse/selectAll');
        if (response.status === 200) {
            if (Array.isArray(response.data.data)) {
                greenhouses.value = response.data.data;
            } else {
                ElMessage.error('返回的数据格式不正确');
            }
        } else {
            ElMessage.error(response.data.message || '获取数据失败');
        }
    } catch (error) {
        ElMessage.error('请求失败，请检查网络');
        console.error('请求失败:', error);
    }
};

onMounted(() => {
    fetchGreenhouses();
});

const handleConfirm = async () => {
    try {
        if (form.id) {
            // 编辑操作
            const response = await get('/greenhouse/update', form);
            if (response.status === 200) {
                ElMessage.success('编辑成功');
            } else {
                ElMessage.error(response.data.message || '编辑失败');
            }
        } else {
            // 新增操作
            const response = await get('/greenhouse/add', form);
            if (response.status === 200) {
                ElMessage.success('新增成功');
            } else {
                ElMessage.error(response.data.message || '新增失败');
            }
        }
        // 重新获取大棚列表
        fetchGreenhouses();
        // 关闭对话框
        dialogVisible.value = false;
    } catch (error) {
        ElMessage.error('操作失败，请检查网络');
        console.error('操作失败:', error);
    }
};

const handleDelete = async (row) => {
    try {
        const response = await get(`/greenhouse/delete?id=${row.id}`);
        if (response.status === 200) {
            ElMessage.success('删除成功');
            // 重新获取大棚列表
            fetchGreenhouses();
        } else {
            ElMessage.error(response.data.message || '删除失败');
        }
    } catch (error) {
        ElMessage.error('操作失败，请检查网络');
        console.error('操作失败:', error);
    }
};

const handleChangeStatus = async (row) => {
    try {
        const response = await get(`/greenhouse/status?id=${row.id}&status=${row.status}`);
        if (response.status === 200) {
            ElMessage.success('状态更新成功');
        } else {
            ElMessage.error(response.data.message || '状态更新失败');
            // 如果更新失败，恢复原来的状态
            row.status = row.status === '1' ? '0' : '1';
        }
    } catch (error) {
        ElMessage.error('操作失败，请检查网络');
        console.error('操作失败:', error);
        // 如果请求失败，恢复原来的状态
        row.status = row.status === '1' ? '0' : '1';
    }
};
</script>
<style lang="scss" scoped>
.greenhouse-container {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中 */
    flex-direction: column;
    /* 使子元素垂直排列 */
    margin-top: 100px;
    /* 调整与Header的距离 */

}

.greenhouse {

    max-width: 1500px;
    width: 100%;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    background-color: #fff;
    border-radius: 4px;
}

.button-container {
    text-align: right;
    margin-bottom: 10px;
}



/* 鼠标悬停效果 */
.el-table tbody tr:hover {
    background-color: #f5f5f5;
}

.table {
    width: 100%;
    display: flex;
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中 */
    flex-direction: column;

}
</style>